package io.finer.erp.jeecg.bas.service.impl;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.api.client.util.Maps;
import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import io.finer.erp.jeecg.bas.dto.MaterialDTO;
import io.finer.erp.jeecg.bas.entity.BasMaterial;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.entity.BasMaterialTemp;
import io.finer.erp.jeecg.bas.entity.ErpSysRole;
import io.finer.erp.jeecg.bas.entity.ZrkMesFqParam;
import io.finer.erp.jeecg.bas.entity.ZrkOrderProduct;
import io.finer.erp.jeecg.bas.entity.ZrkProductCustomer;
import io.finer.erp.jeecg.bas.entity.ZrkQzOrdeDetail;
import io.finer.erp.jeecg.bas.entity.ZrkQzOrder;
import io.finer.erp.jeecg.bas.entity.ZrkShoporder;
import io.finer.erp.jeecg.bas.entity.ZzDeviceType;
import io.finer.erp.jeecg.bas.entity.ZzShoporder;
import io.finer.erp.jeecg.bas.mapper.ZrkQzOrdeDetailMapper;
import io.finer.erp.jeecg.bas.mapper.ZrkQzOrderMapper;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.bas.service.IBasMaterialTempService;
import io.finer.erp.jeecg.bas.service.IErpSysService;
import io.finer.erp.jeecg.bas.service.IZrkMesFqParamService;
import io.finer.erp.jeecg.bas.service.IZrkOrderProductService;
import io.finer.erp.jeecg.bas.service.IZrkProductCustomerService;
import io.finer.erp.jeecg.bas.service.IZrkQzOrderService;
import io.finer.erp.jeecg.bas.service.IZrkShoporderService;
import io.finer.erp.jeecg.bas.service.IZzDeviceTypeService;
import io.finer.erp.jeecg.bas.service.IZzShoporderService;
import io.finer.erp.jeecg.bas.vo.CreateMesVO;
import io.finer.erp.jeecg.bas.vo.PickUpVo;
import io.finer.erp.jeecg.bas.vo.ProductCustomVO;
import io.finer.erp.jeecg.stock.entity.StkInventory;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.entity.StkIoBillEntry;
import io.finer.erp.jeecg.stock.entity.StkPickUpBill;
import io.finer.erp.jeecg.stock.entity.StkPickUpEntry;
import io.finer.erp.jeecg.stock.mapper.StkIoBillMapper;
import io.finer.erp.jeecg.stock.service.IStkInventoryService;
import io.finer.erp.jeecg.stock.service.IStkIoBillEntryService;
import io.finer.erp.jeecg.stock.service.IStkIoBillService;
import io.finer.erp.jeecg.stock.service.IStkPickUpBillService;
import io.finer.erp.jeecg.stock.service.IStkPickUpEntryService;

/**
 * @Description: 分切/切张单
 * @Author: jeecg-boot
 * @Date:   2020-10-14
 * @Version: V1.0
 */
@Service
public class ZrkQzOrderServiceImpl extends ServiceImpl<ZrkQzOrderMapper, ZrkQzOrder> implements IZrkQzOrderService {

	@Autowired
	private ZrkQzOrderMapper zrkQzOrderMapper;
	@Autowired
	private ZrkQzOrdeDetailMapper zrkQzOrdeDetailMapper;
	@Autowired
	private IZzShoporderService shopOrderService;
	@Autowired
	private IStkPickUpBillService pickUpService;
	@Autowired
	private IStkPickUpEntryService pickUpEntryService;
	@Autowired
	private IBasMaterialCategoryService categoryService;
	@Autowired
	private IBasMaterialService materialService;
	@Autowired
	private IBasMaterialTempService tempService;
	@Autowired
	private IStkInventoryService inventoryService;
	@Autowired
	private IZrkMesFqParamService fqParamService;
	@Autowired
	private IZrkProductCustomerService zrkProductCustomerService;
	@Autowired
	private IStkIoBillService ioBillService;
	@Autowired
	private StkIoBillMapper ioBillMapper;
	@Autowired
	private IStkIoBillEntryService entryService;
	@Autowired
	private ISysBaseAPI iSysBaseAPI;
	@Autowired
	private IZrkOrderProductService zrkOrderProductService;
	@Autowired
    private IZrkShoporderService zrkShoporderService;
	@Autowired
	private IZzDeviceTypeService deviceTypeService;
	@Autowired
	private IErpSysService erpSysService;
	@Autowired
	private ISysBaseAPI baseApi;

	
	@Override
	public List<ZrkQzOrder> getQzOrderByOrderId(String orderId) {
		return this.baseMapper.getQzOrderByOrderId(orderId);
	}
	
	@Override
	@Transactional
	public void saveMain(ZrkQzOrder zrkQzOrder, List<ZrkQzOrdeDetail> zrkQzOrdeDetailList) {
		zrkQzOrderMapper.insert(zrkQzOrder);
		if(zrkQzOrdeDetailList!=null && zrkQzOrdeDetailList.size()>0) {
			for(ZrkQzOrdeDetail entity:zrkQzOrdeDetailList) {
				//外键设置
				entity.setZrkQzOrderId(zrkQzOrder.getId());
				zrkQzOrdeDetailMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(ZrkQzOrder zrkQzOrder,List<ZrkQzOrdeDetail> zrkQzOrdeDetailList) {
		zrkQzOrderMapper.updateById(zrkQzOrder);
		//1.先删除子表数据
		zrkQzOrdeDetailMapper.deleteByMainId(zrkQzOrder.getId());
		
		//2.子表数据重新插入
		if(zrkQzOrdeDetailList!=null && zrkQzOrdeDetailList.size()>0) {
			for(ZrkQzOrdeDetail entity:zrkQzOrdeDetailList) {
				//外键设置
				entity.setZrkQzOrderId(zrkQzOrder.getId());
				zrkQzOrdeDetailMapper.insert(entity);
			}
		}
	}
	
	@Override
	public ZrkQzOrder checkByOrderProcessId(String orderProcessId) {
		LambdaQueryWrapper<ZrkQzOrder> query = new LambdaQueryWrapper<>();
		query.eq(ZrkQzOrder::getOrderProcessId, orderProcessId);
		List<ZrkQzOrder> list = this.list(query);
		if(null != list && 0 != list.size()) {
			return list.get(0);
		}
		return null;
	}

	@Override
	@Transactional
	public void delMain(String id) {
		zrkQzOrdeDetailMapper.deleteByMainId(id);
		zrkQzOrderMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			zrkQzOrdeDetailMapper.deleteByMainId(id.toString());
			zrkQzOrderMapper.deleteById(id);
		}
	}

	@Override
	@Transactional
	public Result<?> createMesFHQZ(CreateMesVO createMes) {
		System.out.println("-------------------------------------------");
		System.out.println(JSON.toJSONString(createMes));
		String orderId = createMes.getOrderId();
		String deviceId = createMes.getDeviceId();
		String userId = createMes.getUserId();
		String remark = createMes.getRemark();
		String amountOfGlue = createMes.getAmountOfGule();
		List<PickUpVo> pickUps = createMes.getList();
		if(StringUtils.isBlank(orderId) || StringUtils.isBlank(deviceId) || StringUtils.isBlank(userId)) {
			return Result.error("请填写正确的信息");
		}
		if(pickUps == null || pickUps.size() == 0) {
			return Result.error("请填写提货信息");
		}
//		for (PickUpVo pickUpVo : pickUps) {
//			if((StringUtils.isBlank(pickUpVo.getCategoryId()) || 
//					StringUtils.isBlank(pickUpVo.getModel()) || 
//					null == pickUpVo.getNumber()) || StringUtils.isBlank(pickUpVo.getMaterialCode())) {
//				return Result.error("请填写正确的提货信息");
//			}
//		}
		ZzShoporder shoporder = this.shopOrderService.getById(orderId);
		if(null == shoporder) {
			return Result.error("未找到生产单");
		}
		ZrkQzOrder check = this.getByOrderId(orderId);
		if(null != check&&"0".equals(check.getDelFlag())) {
			return Result.error("不能连续提交");
		}
		String mesCode = "";
		String processId = shoporder.getProcessId();
		boolean flag = true;
		ZzDeviceType process = this.deviceTypeService.getById(processId);
		if(null != process) {
			String processName = process.getDeviceTpyeName();
			if(StringUtils.isNotBlank(processName) && StringUtils.contains(processName, "复合")) {
				mesCode = this.baseApi.getNoByCode("mes_fh_code");
				flag = false;
			}
			if(StringUtils.isNotBlank(processName) && StringUtils.contains(processName, "切张")) {
				mesCode = this.baseApi.getNoByCode("mes_qz_code");
				flag = false;
			}
		}
		if(flag) {
			mesCode = this.baseApi.getNoByCode("mes_code");
		}
		
			
		ZrkQzOrder mes = new ZrkQzOrder();
		
		mes.setOperatorUsers(userId);
		mes.setMachineId(deviceId);
		mes.setCode(mesCode);
		mes.setMaterialId(shoporder.getCategoryId());
		mes.setFormulaId(shoporder.getFormulaId());
		mes.setIsFinish(0);
		mes.setIsPush(1);
		mes.setIsSalary("1");
		mes.setWoDeliverytime(shoporder.getWoPlanendtime());
		mes.setCustomerName(shoporder.getCustomerName());
		mes.setProcessId(shoporder.getProcessId());
		mes.setSort(createMes.getSort());
		mes.setRemark(remark);
		mes.setAmountOfGlue(amountOfGlue);
		mes.setOrderProcessId(shoporder.getId());
		mes.setMesOrderStatus("1");
		if(null != shoporder.getWoQuantity()) {
			mes.setProductNum(new BigDecimal(shoporder.getWoQuantity()));
		}
		mes.setSpecs(shoporder.getSpecs());
		this.save(mes);//新增mes单
		//新增提货单
		StkPickUpBill pickUpBill = new StkPickUpBill();
		pickUpBill.setProcessId(shoporder.getProcessId());
		pickUpBill.setOrderId(shoporder.getId());
		pickUpBill.setBillStatus("0");
		String billNo = this.baseApi.getNoByCode("pick_up_bill_no");
		pickUpBill.setBillNo(billNo);
		pickUpBill.setDeviceId(mes.getMachineId());
		pickUpBill.setIsEnabled(1);
		pickUpBill.setMesId(mes.getId());
		pickUpBill.setType("0");
		this.pickUpService.save(pickUpBill);
		List<StkPickUpEntry> entryList = Lists.newArrayList();
		for (PickUpVo pickUpVo : pickUps) {
			String materialCodes = pickUpVo.getMaterialCode();
			if(StringUtils.isBlank(materialCodes) && (null == pickUpVo.getNumber() || BigDecimal.ZERO.compareTo(pickUpVo.getNumber()) >= 0)) {
				continue;
			}
			if(StringUtils.isBlank(materialCodes)) {
				String categoryId = pickUpVo.getCategoryId();
				BasMaterialCategory category = this.categoryService.getById(categoryId);
				StkPickUpEntry entry = new StkPickUpEntry();
				entry.setBillId(pickUpBill.getId());
				entry.setIsOut("0");
				entry.setNumber(pickUpVo.getNumber());
				entry.setUnitId(category.getUnitId());
				entry.setCategoryId(pickUpVo.getCategoryId());
				entry.setModel(pickUpVo.getModel());
				entry.setRemark(pickUpVo.getRemark());
				entryList.add(entry);
			} else {
				String[] materialCodeArray = StringUtils.split(materialCodes, ",");
				for (int i = 0; i < materialCodeArray.length; i++) {
					String code = materialCodeArray[i];
					BasMaterial material = materialService.getMaterialByCode(code);
					String materialId = material.getId();
					StkInventory inventory = inventoryService.selectLatestByMaterial(materialId);
					StkPickUpEntry entry = new StkPickUpEntry();
					entry.setBillId(pickUpBill.getId());
					entry.setIsOut("0");
					entry.setUnitId(material.getUnitId());
					entry.setMaterialCode(code);
					entry.setMaterialId(materialId);
					entry.setWarehouseId(inventory.getWarehouseId());
					entry.setModel(material.getModel());
					entry.setRemark(pickUpVo.getRemark());
					entryList.add(entry);
				}
			}
		}
		this.pickUpEntryService.saveBatch(entryList);
		
		//修改生产工单状态
		shoporder.setWoStatus(2);
		shopOrderService.updateById(shoporder);
		//发送生成mes单消息
		iSysBaseAPI.sendCreateMesMessage(mes.getId());
		//发送提货消息
		iSysBaseAPI.sendDdMessage(pickUpBill.getId(),orderId);
		return Result.ok("操作成功");
	}

	@Override
	@Transactional
	public Result<?> createMesFQ(CreateMesVO createMes) {
		// TODO Auto-generated method stub
		System.out.println("-------------------------------------------");
		System.out.println(JSON.toJSONString(createMes));
		String orderIds = createMes.getOrderId();
		String userId = createMes.getUserId();
		String deviceId = createMes.getDeviceId();
		String remark = createMes.getRemark();
		String cateId = null;
		if(StringUtils.isBlank(orderIds) || StringUtils.isBlank(userId) || StringUtils.isBlank(deviceId)) {
			return Result.error("请填写正确的参数");
		}
		List<PickUpVo> list = createMes.getList();
		if(null == list || 0 == list.size()) {
			return Result.error("请填写正确的参数");
		}
		String[] orderIdArray = StringUtils.split(orderIds, ",");
		List<String> orderIdList = Arrays.asList(orderIdArray);
		List<ZrkQzOrder> byOrderIds = getByOrderIds(orderIdList);
        if(null != byOrderIds && byOrderIds.size() > 0) {
        for (ZrkQzOrder byOrderId : byOrderIds) {
            if("0".equals(byOrderId.getDelFlag())){
                    return Result.error("不能连续提交");
                }
            }
        }
		LambdaQueryWrapper<ZzShoporder> orderQuery = new LambdaQueryWrapper<>();
		orderQuery.in(ZzShoporder::getId, orderIdList);
		List<ZzShoporder> orderList = this.shopOrderService.list(orderQuery);
		String cate = null;
		Date minEndDate = null;//生产完成日期
		String processId = null;
//		Date planEndTime=null;
		
		String fomulaId = null;
		String taskCategoryId=null;
		List<String> customerNameList = CollUtil.newArrayList();
		String orderNo = "";
		List<String> orderNoList = Lists.newArrayList();
		for (int i = 0; i < orderList.size(); i++) {
			ZzShoporder shoporder = orderList.get(i);
			fomulaId = shoporder.getFormulaId();
			Date woPlanendtime = shoporder.getWoPlanendtime();
			taskCategoryId = shoporder.getCategoryId();
//			planEndTime=shoporder.getWoPlanendtime();
			cateId = taskCategoryId;
			processId = shoporder.getProcessId();
			if(i == 0) {
				minEndDate = woPlanendtime;
				cate = taskCategoryId;
				customerNameList.add(shoporder.getCustomerName());
			} else {
				if(!taskCategoryId.equals(cate)) {
					return Result.error("产品不同，不能合并生产");
				}
				if(minEndDate.compareTo(woPlanendtime) > 0) {
					minEndDate = woPlanendtime;
				}
				if(!customerNameList.contains(shoporder.getCustomerName())) {
					customerNameList.add(shoporder.getCustomerName());
				}
			}
			if(!orderNoList.contains(shoporder.getOrderNo())) {
				orderNoList.add(shoporder.getOrderNo());
				orderNo = orderNo + shoporder.getOrderNo() + ";";
			}
		}
		String customerName = StringUtils.EMPTY;
		if(CollUtil.isNotEmpty(customerNameList)) {
			customerName = CollUtil.join(customerNameList, ",");
		}
		
		ZrkQzOrder mes = new ZrkQzOrder();
		String mesCode = this.baseApi.getNoByCode("mes_fq_code");
		mes.setOperatorUsers(userId);
		mes.setMachineId(deviceId);
		mes.setCode(mesCode);
		mes.setMaterialId(cate);
		mes.setIsFinish(0);
		mes.setIsPush(1);
		mes.setIsSalary("1");
		mes.setWoDeliverytime(minEndDate);
		mes.setCustomerName(customerName);
		mes.setRemark(remark);
		mes.setProcessId(processId);
		mes.setOrderProcessId(orderIds);
		mes.setMesOrderStatus("1");
		mes.setFormulaId(fomulaId);
		this.save(mes);//新增mes单
		
		//新增提货单
		StkPickUpBill pickUpBill = new StkPickUpBill();
		pickUpBill.setProcessId(processId);
		pickUpBill.setOrderId(orderIds);
		pickUpBill.setBillStatus("0");
		String billNo = this.baseApi.getNoByCode("pick_up_bill_no");
		pickUpBill.setBillNo(billNo);
		pickUpBill.setDeviceId(mes.getMachineId());
		pickUpBill.setIsEnabled(1);
		pickUpBill.setType("0");
		pickUpBill.setMesId(mes.getId());
		this.pickUpService.save(pickUpBill);
		
		List<PickUpVo> pickUpList = createMes.getList();
		List<StkPickUpEntry> entryList = Lists.newArrayList();
		List<PickUpVo> partList = createMes.getPartList();
		//编辑分切参数及提货单详情
		for (PickUpVo pickUpVo : pickUpList) {
			String materialCodes = pickUpVo.getMaterialCode();
			if(StringUtils.isBlank(materialCodes)) {
				String categoryId = pickUpVo.getCategoryId();
				BasMaterialCategory category = this.categoryService.getById(categoryId);
				StkPickUpEntry entry = new StkPickUpEntry();
				entry.setBillId(pickUpBill.getId());
				entry.setIsOut("0");
				entry.setNumber(pickUpVo.getNumber());
				entry.setUnitId(category.getUnitId());
				entry.setCategoryId(categoryId);
				entry.setModel(pickUpVo.getModel());
				entry.setRemark(pickUpVo.getRemark());
				entryList.add(entry);
			} else {
				String[] materialCodeArray = StringUtils.split(materialCodes, ",");
				for (int i = 0; i < materialCodeArray.length; i++) {
					String code = materialCodeArray[i];
					BasMaterial material = materialService.getMaterialByCode(code);
					String materialId = material.getId();
					StkInventory inventory = inventoryService.selectLatestByMaterial(materialId);
					StkPickUpEntry entry = new StkPickUpEntry();
					entry.setBillId(pickUpBill.getId());
					entry.setIsOut("0");
					entry.setUnitId(material.getUnitId());
					entry.setMaterialCode(code);
					entry.setMaterialId(materialId);
					entry.setWarehouseId(inventory.getWarehouseId());
					entry.setModel(material.getModel());
					entry.setRemark(pickUpVo.getRemark());
					entryList.add(entry);
				}
			}
		}
		this.pickUpEntryService.saveBatch(entryList);
		BasMaterialCategory category = this.categoryService.getById(cateId);
		List<ZrkMesFqParam> params = Lists.newArrayList();
		for (PickUpVo pickUpVo : partList) {
			ZrkMesFqParam param = new ZrkMesFqParam();
			param.setMesId(mes.getId());
			param.setPartParam(pickUpVo.getPartParam());
			param.setCategoryId(cateId);
			param.setModel(pickUpVo.getModel());
			param.setQuantity(pickUpVo.getNumber());
			param.setUnitId(category.getUnitId());
			param.setRemark(pickUpVo.getRemark());
			param.setWidth(pickUpVo.getWidth());
			param.setHeight(pickUpVo.getHeight());
			fqParamService.save(param);
//			params.add(param);
		}
//		this.fqParamService.saveBatch(params);
		List<ProductCustomVO> customList = createMes.getCustomerList();
		if(CollUtil.isNotEmpty(customList)) {
			List<ZrkProductCustomer> customers = Lists.newLinkedList();
			for (ProductCustomVO vo : customList) {
				ZrkProductCustomer zrkproductCustomer = new ZrkProductCustomer();
				zrkproductCustomer.setMesId(mes.getId());
				zrkproductCustomer.setWidth(vo.getWidth());
				zrkproductCustomer.setLength(vo.getHeight());
				zrkproductCustomer.setCustomId(vo.getCustomId());
				zrkproductCustomer.setProductNumber(vo.getProductNumber());
				String categoryId = vo.getCategoryId();
				if(StringUtils.isBlank(categoryId)) {
					zrkproductCustomer.setCategoryId(cate);
				}else {
					zrkproductCustomer.setCategoryId(categoryId);
				}
				zrkproductCustomer.setModel(vo.getModel());
				zrkproductCustomer.setRemark(vo.getRemark());
				customers.add(zrkproductCustomer);
			}
			zrkProductCustomerService.saveBatch(customers);
		}
		//修改生产工单状态
		for (int i = 0; i < orderList.size(); i++) {
			ZzShoporder shoporder = orderList.get(i);
			shoporder.setWoStatus(2);
			shopOrderService.updateById(shoporder);
			
		}
		//任务单生成Mes单钉钉消息提醒
		iSysBaseAPI.sendCreateMesMessage(mes.getId());
		//发送提货消息
		iSysBaseAPI.sendDdMessage(pickUpBill.getId(), orderIds);
		return Result.ok("成功");
	}
	
	private ZrkQzOrder getByOrderId(String orderId) {
		LambdaQueryWrapper<ZrkQzOrder> query = new LambdaQueryWrapper<>();
		query.eq(ZrkQzOrder::getOrderProcessId, orderId);
		List<ZrkQzOrder> list = list(query);
		if(null != list && 0 != list.size()) {
			return list.get(0);
		}
			
		return null;
	}
	
	private List<ZrkQzOrder> getByOrderIds(List<String> orderIds) {
		List<ZrkQzOrder> list = Lists.newArrayList();
		for (String orderId : orderIds) {
			LambdaQueryWrapper<ZrkQzOrder> query = new LambdaQueryWrapper<>();
			query.like(ZrkQzOrder::getOrderProcessId, orderId);
			List<ZrkQzOrder> result = list(query);
			if(null != result) {
				list.addAll(result);
			}
		}
		return list;
	}

	@Override
	public boolean changeStatusToProducing(String id) {
		return changeOrderStatus(id, "3",null);
	}
	
	public boolean changeOrderStatus(String id, String status,String[] userIds) {
		ZrkQzOrder order = getById(id);
		if(null == order) {
			return false;
		}
		order.setMesOrderStatus(status);
		if("4".equals(status)) {
			order.setIsFinish(1);
			order.setSort("99");
		}
		String operatorUsers="";
		StringBuffer stringBuffer=new StringBuffer();
		if(userIds !=null && userIds.length>0){
			for (int i=0; i<userIds.length;i++) {
				stringBuffer.append(userIds[i]).append(",");

//				operatorUsers  += userId+",";
			}
			if(stringBuffer.length()>0){
				stringBuffer.replace(stringBuffer.length() - 1, stringBuffer.length(), "");
			}
			if(StringUtils.isNotBlank(stringBuffer.toString())){
				order.setOperatorUsers(stringBuffer.toString());
			}
		}

		boolean flag=true;
		if(StringUtils.isNotBlank(order.getParentId())){
			List<ZrkQzOrder> list=getQzOrderByParentId(order.getParentId());
			for (ZrkQzOrder zrkQzOrder : list) {
				if(!zrkQzOrder.getMesOrderStatus().equals("4")){
					flag=false;
				}
			}
		}
		if(flag){
			String[] orderIds=order.getOrderProcessId().split(",");
			for (String orderId : orderIds) {
                ZzShoporder zzShoporder = new ZzShoporder();
                zzShoporder.setId(orderId);
                zzShoporder.setWoStatus(2);
                shopOrderService.updateById(zzShoporder);
                ZzShoporder zzShoporder1 = shopOrderService.getById(orderId);
                if (zzShoporder1!=null) {
                    ZrkOrderProduct zrkOrderProduct = zrkOrderProductService.getById(zzShoporder1.getOrderProdect());
                    if (zrkOrderProduct != null) {
                        zrkOrderProduct.setIsStatus("1");
                        zrkOrderProductService.updateById(zrkOrderProduct);
                    }
                    LambdaQueryWrapper<ZrkOrderProduct> query = new LambdaQueryWrapper<>();
                    query.like(ZrkOrderProduct::getId, zzShoporder1.getOrderProdect());
                    List<ZrkOrderProduct> zrkOrderProducts=zrkOrderProductService.list(query);
                    boolean flag1=true;
                    for (ZrkOrderProduct zrkOrderProduct1 : zrkOrderProducts) {
                        if(zrkOrderProduct1.getIsStatus().equals("0")){
                            flag1=false;
                        }
                    }
                    if(flag1 && zrkOrderProduct!=null){
                        ZrkShoporder zrkShoporder=zrkShoporderService.getById(zrkOrderProduct.getOrderId());
                        if(zrkShoporder!=null) {
                            zrkShoporder.setOrderStatus("9");
                            zrkShoporderService.updateById(zrkShoporder);
                        }
                    }
                }
            }
		}
		return this.updateById(order);
	}

	@Override
	public List<MaterialDTO> getMesMaterial(String id) {
		ZrkQzOrder qzOrder = getById(id);
		if(qzOrder!=null) {
			List<MaterialDTO> result = Lists.newArrayList();
			if(StringUtils.equals("1300701144731623426", qzOrder.getProcessId())
					|| StringUtils.equals("1300701196116041729", qzOrder.getProcessId())) {
				if(oConvertUtils.isEmpty(qzOrder.getParentId())) {
					result = getQZMaterialDTO(qzOrder);
					
				}else {
					while(!oConvertUtils.isEmpty(qzOrder.getParentId())) {
						qzOrder = getById(qzOrder.getParentId());
						if(qzOrder!=null&&StringUtils.equals(qzOrder.getDelFlag(), "0")) {
							result = getQZMaterialDTO(qzOrder);
						}else {
							break;
						}
						if(StringUtils.equals("0", qzOrder.getParentId())) {
							break;
						}
					}
				}
			}else {
				if(oConvertUtils.isEmpty(qzOrder.getParentId())) {
					result = getMaterialDTO(qzOrder);
					
				}else {
					while(!oConvertUtils.isEmpty(qzOrder.getParentId())) {
						qzOrder = getById(qzOrder.getParentId());
						if(qzOrder!=null&&StringUtils.equals(qzOrder.getDelFlag(), "0")) {
							result = getMaterialDTO(qzOrder);
						}else {
							break;
						}
						if(StringUtils.equals("0", qzOrder.getParentId())) {
							break;
						}
					}
				}
			}
			
			if(result!=null&&result.size()>0) {
				return result;
			}
		}
		return null;
	}

	private List<MaterialDTO> getMaterialDTO(ZrkQzOrder zrkQzOrder){
		String mesCode = zrkQzOrder.getCode();
		LambdaQueryWrapper<StkIoBill> billQuery = new LambdaQueryWrapper<>();
		billQuery.eq(StkIoBill::getSourceNo, mesCode);
		List<StkIoBill> billList = this.ioBillService.list(billQuery);
		if(null != billList && 0 != billList.size()) {
			List<String> billIdList = Lists.newArrayList();
			for (StkIoBill stkIoBill : billList) {
				String stockIoType = stkIoBill.getStockIoType();
				if(StrUtil.startWith(stockIoType, "2")) {
					billIdList.add(stkIoBill.getId());
				}
			}
			if(billIdList!=null&&billIdList.size()>0) {
				LambdaQueryWrapper<StkIoBillEntry> entryQuery = new LambdaQueryWrapper<>();
				entryQuery.in(StkIoBillEntry::getMid, billIdList);
				List<StkIoBillEntry> list = this.entryService.list(entryQuery);
				if(null != list && 0 != list.size()) {
					List<MaterialDTO> result = Lists.newArrayList();
					for (StkIoBillEntry entry : list) {
						MaterialDTO material = new MaterialDTO();
						BasMaterial basMaterial = materialService.getById(entry.getMaterialId());
						if(null != basMaterial) {
							material.setCode(basMaterial.getCode());
							material.setId(basMaterial.getId());
							material.setName(basMaterial.getName());
							material.setWidth(basMaterial.getWidth());
							material.setLength(basMaterial.getLength());
							material.setModel(basMaterial.getModel());
							material.setNumber(entry.getQty());
							result.add(material);
						}
					}
					return result;
				}
			}
		}
		return null;
	}
	
	
	private List<MaterialDTO> getQZMaterialDTO(ZrkQzOrder zrkQzOrder){
		String mesCode = zrkQzOrder.getCode();
		LambdaQueryWrapper<StkIoBill> billQuery = new LambdaQueryWrapper<>();
		billQuery.eq(StkIoBill::getSourceNo, mesCode);
		List<StkIoBill> billList = this.ioBillService.list(billQuery);
		if(null != billList && 0 != billList.size()) {
			List<String> billIdList = Lists.newArrayList();
			for (StkIoBill stkIoBill : billList) {
				String stockIoType = stkIoBill.getStockIoType();
				if(StrUtil.startWith(stockIoType, "2")) {
					billIdList.add(stkIoBill.getId());
				}
			}
			if(billIdList!=null&&billIdList.size()>0) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				LambdaQueryWrapper<StkIoBillEntry> entryQuery = new LambdaQueryWrapper<>();
				entryQuery.in(StkIoBillEntry::getMid, billIdList);
				List<StkIoBillEntry> list = this.entryService.list(entryQuery);
				if(null != list && 0 != list.size()) {
					List<MaterialDTO> result = Lists.newArrayList();
					Map<String, String> dateMap = Maps.newHashMap();//临时存放对应物料复合时间
					Map<String, String> fMap = Maps.newHashMap();//临时存放对应物料复合配方
					for (StkIoBillEntry entry : list) {
						MaterialDTO material = new MaterialDTO();
						BasMaterial basMaterial = materialService.getById(entry.getMaterialId());
						if(null != basMaterial) {
							material.setCode(basMaterial.getCode());
							material.setId(basMaterial.getId());
							material.setName(basMaterial.getName());
							material.setWidth(basMaterial.getWidth());
							material.setLength(basMaterial.getLength());
							material.setModel(basMaterial.getModel());
							material.setNumber(entry.getQty());
							result.add(material);
							if(StringUtils.isNotBlank(basMaterial.getPid())) {
								List<String> materialIdList = Arrays.asList(StringUtils.split(basMaterial.getId(), ","));
								List<BasMaterial> materialList = materialService.listByIds(materialIdList);
								List<String> mIdList = Lists.newArrayList();
								if(materialList!=null && materialList.size()>0) {
									StringBuffer materDate = new StringBuffer();
									StringBuffer formu = new StringBuffer();
									for(BasMaterial bas:materialList) {
										mIdList.add(bas.getId());
										materDate.append(format.format(bas.getCreateTime()));
										materDate.append(",");
										if(StringUtils.isNotBlank(bas.getFormulaId())) {
											formu.append(bas.getFormulaId());
											formu.append(",");
										}
									}
									List<StkIoBill> ioBillList = ioBillMapper.selectBatchByMaterialIdList(materialIdList, "1992");
									if(ioBillList!=null && ioBillList.size()>0) {
										if(materDate!=null && materDate.length()>0) {
											String mDate = materDate.toString().substring(0, materDate.length()-1);
											dateMap.put(basMaterial.getId(), mDate);
										}
										if(formu!=null && formu.length()>0) {
											String formulaStr = formu.toString().substring(0, formu.length()-1);
											fMap.put(basMaterial.getId(), formulaStr);
										}
									}else {
										List<BasMaterial> mList = materialService.listByIds(materialIdList);
										StringBuffer materialDate = new StringBuffer();
										StringBuffer formula = new StringBuffer();
										if(mList!=null && mList.size()>0) {
											for(BasMaterial bas:mList) {
												materialDate.append(format.format(bas.getCreateTime()));
												materialDate.append(",");
												if(StringUtils.isNotBlank(bas.getFormulaId())) {
													formula.append(bas.getFormulaId());
													formula.append(",");
												}
											}
											if(materialDate!=null && materialDate.length()>0) {
												String mDate = materialDate.toString().substring(0, materialDate.length()-1);
												dateMap.put(basMaterial.getId(), mDate);
											}
											if(formula!=null && formula.length()>0) {
												String formulaStr = formula.toString().substring(0, formula.length()-1);
												fMap.put(basMaterial.getId(), formulaStr);
											}
										}
									}
									
								}
							}
						}
					}
					if(result!=null && result.size()>0) {
						for(MaterialDTO dto:result) {
							dto.setFhTime(dateMap.get(dto.getId()));
							dto.setFhFormula(fMap.get(dto.getId()));
						}
					}
					return result;
				}
			}
		}
		return null;
	}

	@Override
	public List<ZrkQzOrder> getQzOrderByOrderProcessId(String id){
		return zrkQzOrderMapper.getQzOrderByOrderProcessId(id);
	}

	@Override
	public List<ZrkQzOrder> getQzOrderByParentId(String parentId){
		return zrkQzOrderMapper.getQzOrderByParentId(parentId);
	}



	@Override
	public List<String> getMesMaterials(String id) {
		ZrkQzOrder qzOrder = getById(id);
		if(qzOrder!=null) {
			if(oConvertUtils.isEmpty(qzOrder.getParentId())) {
				List<String> result = getMatetialList(qzOrder);
				if(result!=null&&result.size()>0) {
					return result;
				}
			}else {
				ZrkQzOrder order = getById(qzOrder.getParentId());
				if(order!=null&&StringUtils.equals(order.getDelFlag(), "0")) {
					List<String> result = getMatetialList(order);
					if(result!=null&&result.size()>0) {
						return result;
					}
				}
			}
		}
		return null;
	}

	private List<String> getMatetialList(ZrkQzOrder zrkQzOrder){
		String mesCode = zrkQzOrder.getCode();
		LambdaQueryWrapper<StkIoBill> billQuery = new LambdaQueryWrapper<>();
		billQuery.eq(StkIoBill::getSourceNo, mesCode);
		List<StkIoBill> billList = this.ioBillService.list(billQuery);
		if(null != billList && 0 != billList.size()) {
			List<String> billIdList = Lists.newArrayList();
			for (StkIoBill stkIoBill : billList) {
				String stockIoType = stkIoBill.getStockIoType();
				if(StrUtil.startWith(stockIoType, "2")) {
					billIdList.add(stkIoBill.getId());
				}
			}
			billIdList.add(UUID.randomUUID().toString());
			LambdaQueryWrapper<StkIoBillEntry> entryQuery = new LambdaQueryWrapper<>();
			entryQuery.in(StkIoBillEntry::getMid, billIdList);
			List<StkIoBillEntry> list = this.entryService.list(entryQuery);
			if(null != list && 0 != list.size()) {
				List<String> result = Lists.newArrayList();
				for (StkIoBillEntry entry : list) {
					StkPickUpEntry material = new StkPickUpEntry();
					BasMaterial basMaterial = materialService.getById(entry.getMaterialId());
					if(null != basMaterial) {
						material.setCategoryId(basMaterial.getCategoryId());
						result.add(material.getCategoryId());
						BasMaterialCategory cate = categoryService.getById(material.getCategoryId());
						if(cate!=null) {
							result.add(cate.getPid());
						}
					}
				}

				return result.stream().distinct().collect(Collectors.toList());
			}
		}
		return null;
	}

	@Override
	public ZrkQzOrder getByCode(String code) {
		return lambdaQuery().eq(ZrkQzOrder::getCode, code).one();
	}

	@Override
	@Transactional
	public Result<?> updateSortAsc(ZrkQzOrder zrkQzOrder) {
		// TODO Auto-generated method stub
		QueryWrapper<ZrkQzOrder> queryWrapper = new QueryWrapper<>();
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();//获取登录用户信息
		//admin可以查看所有，此处排除admin用户的权限检测
		boolean flag = true;
		List<ErpSysRole> roleList = this.erpSysService.getRoleByUserId(sysUser.getId());
		if(null != roleList && roleList.size() > 0) {
			for (ErpSysRole erpSysRole : roleList) {
				if("admin".equals(erpSysRole.getRoleCode()) || "productTeamLead".equals(erpSysRole.getRoleCode()) || "productLead".equals(erpSysRole.getRoleCode())) {
					flag = false;
					break;
				}
			}
		}
		String operatorUsers = null;
		if(flag) {
			operatorUsers = sysUser.getId();
		}
		List<ZrkQzOrder> list = baseMapper.getList(operatorUsers, zrkQzOrder.getIsFinish(), zrkQzOrder.getMachineId(), zrkQzOrder.getGlue());
		Map<Integer,ZrkQzOrder> map = Maps.newHashMap();
		Iterator<ZrkQzOrder> iterator = list.iterator();
		int i = 1;
		while(iterator.hasNext()) {
			//将查到的mes单临时储存到map中
			ZrkQzOrder zrk = iterator.next();
			map.put(i, zrk);
			if(StringUtils.equals(zrk.getId(), zrkQzOrder.getId())) {
				zrkQzOrder = zrk;
				break;
			}
			i++;
		}
		//取出当前前段操作的数据和上面一条数据
		ZrkQzOrder qz = map.get(i);
		ZrkQzOrder qzOrder = map.get(i-1);
		if(qz==null) {
			return Result.error("操作失败，未找到当前数据信息");
		}
		if(qzOrder==null) {
			return Result.error("当前mes单已是第一条数据");
		}
		String sort1 = qz.getSort();
		String sort2 = qzOrder.getSort();
		qz.setSort(sort2);
		qzOrder.setSort(sort1);
		baseMapper.updateById(qz);
		baseMapper.updateById(qzOrder);
		return Result.ok("操作成功");
	}

	@Override
	@Transactional
	public Result<?> updateSortDesc(ZrkQzOrder zrkQzOrder) {
		// TODO Auto-generated method stub
		QueryWrapper<ZrkQzOrder> queryWrapper = new QueryWrapper<>();
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();//获取登录用户信息
		//admin可以查看所有，此处排除admin用户的权限检测
		boolean flag = true;
		List<ErpSysRole> roleList = this.erpSysService.getRoleByUserId(sysUser.getId());
		if(null != roleList && roleList.size() > 0) {
			for (ErpSysRole erpSysRole : roleList) {
				if("admin".equals(erpSysRole.getRoleCode()) || "productTeamLead".equals(erpSysRole.getRoleCode()) || "productLead".equals(erpSysRole.getRoleCode())) {
					flag = false;
					break;
				}
			}
			System.err.println("desc当前登录人信息：：：："+roleList);
		}
		String operatorUsers = null;
		if(flag) {
			operatorUsers = sysUser.getId();
		}
		List<ZrkQzOrder> list = baseMapper.getList(operatorUsers, zrkQzOrder.getIsFinish(), zrkQzOrder.getMachineId(), zrkQzOrder.getGlue());
		Map<Integer,ZrkQzOrder> map = Maps.newHashMap();
		Iterator<ZrkQzOrder> iterator = list.iterator();
		int i = 1;
		int j = 0;
		while(iterator.hasNext()) {
			ZrkQzOrder zrk = iterator.next();
			//将查到的mes单临时储存到map中
			map.put(i, zrk);
			if(StringUtils.equals(zrk.getId(), zrkQzOrder.getId())) {
				j = i + 1;
			}
			if(i==j) {
				break;
			}
			i++;
		}
		//取出当前前段操作的数据和下面一条数据
		ZrkQzOrder qz = map.get(i-1);
		ZrkQzOrder qzOrder = map.get(i);
		if(qz==null) {
			return Result.error("操作失败，未找到当前数据信息");
		}
		if(qzOrder==null) {
			return Result.error("当前mes单已是最后一条数据");
		}
		int isFinish = 0;
		if(oConvertUtils.isNotEmpty(qzOrder.getIsFinish())) {
			isFinish = qzOrder.getIsFinish();
		}
		if(oConvertUtils.isEmpty(qzOrder.getSort())||NumberUtil.compare(isFinish, 1)==0) {
			return Result.error("当前mes单已是最后一条数据");
		}
		String sort1 = qz.getSort();
		String sort2 = qzOrder.getSort();
		qz.setSort(sort2);
		qzOrder.setSort(sort1);
		baseMapper.updateById(qz);
		baseMapper.updateById(qzOrder);
		return Result.ok("操作成功");
	}

	@Override
	public IPage<ZrkQzOrder> getPageList(Page<ZrkQzOrder> page, ZrkQzOrder zrkQzOrder) {
		// TODO Auto-generated method stub
		return baseMapper.getPageList(page, zrkQzOrder);
	}

	@Override
	public IPage<ZrkQzOrder> getPageFQList(Page<ZrkQzOrder> page, ZrkQzOrder zrkQzOrder) {
		// TODO Auto-generated method stub
		return baseMapper.getPageFQList(page, zrkQzOrder);
	}
	
	@Override
	public IPage<ZrkQzOrder> getPageQZList(Page<ZrkQzOrder> page, ZrkQzOrder zrkQzOrder) {
		// TODO Auto-generated method stub
		return baseMapper.getPageQZList(page, zrkQzOrder);
	}

	@Override
	@Transactional
	public Result<?> updateUserAndMachine(ZrkQzOrder zrkQzOrder) {
		if(zrkQzOrder==null) {
			Result.error("请选择操作人及机器");
		}
		if(oConvertUtils.isEmpty(zrkQzOrder.getOperatorUsers())) {
			Result.error("请选择操作人");
		}
		if(oConvertUtils.isEmpty(zrkQzOrder.getMachineId())) {
			Result.error("请选择机器");
		}
		if(oConvertUtils.isEmpty(zrkQzOrder.getId())) {
			Result.error("未选择数据");
		}
		ZrkQzOrder qzOrder = baseMapper.selectById(zrkQzOrder.getId());
		if(qzOrder==null) {
			Result.error("选择的数据不存在");
		}
		qzOrder.setOperatorUsers(zrkQzOrder.getOperatorUsers());
		qzOrder.setMachineId(zrkQzOrder.getMachineId());
		baseMapper.updateById(qzOrder);
		//根据mes单id查询提货单
		List<StkPickUpBill> upBillList = pickUpService.getByMesId(qzOrder.getId());
		if(upBillList!=null && upBillList.size()>0) {
			for(StkPickUpBill stkPickUpBill:upBillList) {
				stkPickUpBill.setDeviceId(qzOrder.getMachineId());
			}
			pickUpService.updateBatchById(upBillList);
		}
		//根据mes单id查询物料临时表
		LambdaQueryWrapper<BasMaterialTemp> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(BasMaterialTemp::getProcedureId, qzOrder.getId());
		List<BasMaterialTemp> tempList = tempService.list(queryWrapper);
		if(tempList!=null && tempList.size()>0) {
			for(BasMaterialTemp basMaterialTemp:tempList) {
				basMaterialTemp.setMachine(qzOrder.getMachineId());
			}
			tempService.updateBatchById(tempList);
		}
		return Result.ok("修改成功");
	}

}
